﻿using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using MVAScratchPad.Common;
using MVAScratchPad.ViewModels;
using MVAScratchPad.Services;
using System.ComponentModel;
using System;

namespace MVAScratchPad.Views
{
    public sealed partial class MainPage : Page, INotifyPropertyChanged
    {
        public MainPage()
        {
            InitializeComponent();
            Windows.UI.Xaml.Window.Current.SizeChanged += (s, e) => ScreenHeight = e.Size.Height;
            Windows.UI.Xaml.Window.Current.VisibilityChanged += async (s, e) =>
            {
                await this.ViewModel.SaveState(null);
            };
            App.Current.Suspending += async (s, e) =>
            {
                var d = e.SuspendingOperation.GetDeferral();
                await this.ViewModel.SaveState(null);
                d.Complete();
            };
        }

        private MainPageViewModel ViewModel { get { return DataContext as MainPageViewModel; } }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            await this.ViewModel.LoadState(e);
            this.ViewModel.AddNoteCompleted += (s, a) => { MyHub.ScrollToSection(MyHub.Sections[0]); };
        }

        double _ScreenHeight = Windows.UI.Xaml.Window.Current.Bounds.Height;
        public double ScreenHeight { get { return _ScreenHeight; } set { SetProperty(ref _ScreenHeight, value); } }

        public event PropertyChangedEventHandler PropertyChanged;
        void SetProperty<T>(ref T storage, T value, [System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
        {
            if (!object.Equals(storage, value))
            {
                storage = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}